package com.smart.community.user.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smart.community.commons.exception.BusinessException;
import com.smart.community.user.dto.RoleDTO;
import com.smart.community.user.dto.RoleQueryDTO;
import com.smart.community.user.entity.Role;
import com.smart.community.user.entity.RolePermission;
import com.smart.community.user.mapper.RoleMapper;
import com.smart.community.user.mapper.RolePermissionMapper;
import com.smart.community.user.service.RoleService;
import com.smart.community.user.vo.PageResult;
import com.smart.community.user.vo.RoleVO;

import io.seata.spring.annotation.GlobalTransactional;

/**
 * 角色管理服务实现类
 *
 * @author Wu.Liang
 * @since 2025-07-05
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public PageResult<RoleVO> getRoleList(RoleQueryDTO queryDTO) throws Exception {
        // 获取分页参数，使用规范的current和size
        Integer current = queryDTO.getCurrent();
        Integer size = queryDTO.getSize();
        
        // 参数校验
        if (current == null || current < 1) {
            current = 1;
        }
        if (size == null || size < 1) {
            size = 10;
        }
        
        // 如果size很大（比如9999），则查询所有角色
        if (size > 1000) {
            // 查询所有角色，不分页
            List<Role> allRoles = roleMapper.selectList(null);
            
            // 转换为VO对象
            List<RoleVO> roleVOList = allRoles.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
            
            // 构建分页结果
            PageResult<RoleVO> result = new PageResult<>();
            result.setRecords(roleVOList);
            result.setTotal((long) allRoles.size());
            result.setSize((long) allRoles.size());
            result.setCurrent(1L);
            result.setPages(1L);
            
            return result;
        }
        
        // 正常分页查询
        Page<Role> page = new Page<>(current, size);
        
        // 调用Mapper进行分页查询
        IPage<Role> rolePage = roleMapper.selectRolePage(
            page, 
            queryDTO.getRoleCode(), 
            queryDTO.getRoleName(), 
            queryDTO.getRoleType(), 
            queryDTO.getStatus()
        );
        
        // 转换为VO对象
        List<RoleVO> roleVOList = new ArrayList<>();
        if (rolePage != null && rolePage.getRecords() != null) {
            roleVOList = rolePage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        }
        
        // 构建分页结果
        PageResult<RoleVO> result = new PageResult<>();
        result.setRecords(roleVOList);
        if (rolePage != null) {
            result.setTotal(rolePage.getTotal());
            result.setSize(rolePage.getSize());
            result.setCurrent(rolePage.getCurrent());
            result.setPages(rolePage.getPages());
        } else {
            result.setTotal(0L);
            result.setSize(size.longValue());
            result.setCurrent(current.longValue());
            result.setPages(0L);
        }
        
        return result;
    }

    @Override
    public RoleVO getRole(Long id) throws Exception {
        // 查询角色实体
        Role role = roleMapper.selectById(id);
        if (role == null) {
            return null;
        }
        // 转换为VO对象
        return convertToVO(role);
    }

    // 新增角色方法已移除 - 角色由系统预设，不允许手动创建
    // @Override
    // @GlobalTransactional
    // public void createRole(RoleDTO roleDTO) throws Exception {
    //     // 标准实现：新增角色
    //     Role role = new Role();
    //     BeanUtils.copyProperties(roleDTO, role);
    //     roleMapper.insert(role);
    // }

    @Override
    @GlobalTransactional
    public void updateRole(Long id, RoleDTO roleDTO) throws Exception {
        // 查询现有角色，保留版本号以确保乐观锁正常工作
        Role existingRole = roleMapper.selectById(id);
        if (existingRole == null) {
            throw new BusinessException("角色不存在");
        }
        
        BeanUtils.copyProperties(roleDTO, existingRole);
        roleMapper.updateById(existingRole);
    }

    @Override
    @GlobalTransactional
    public void deleteRole(Long id) throws Exception {
        // 标准实现：删除角色
        roleMapper.deleteById(id);
    }

    @Override
    @GlobalTransactional
    public void updateRoleStatus(Long id, Integer status) throws Exception {
        // 标准实现：更新角色状态
        Role role = new Role();
        role.setId(id);
        role.setStatus(status);
        roleMapper.updateById(role);
    }

    @Override
    public List<Long> getRoleMenus(Long id) throws Exception {
        // 标准实现：获取角色菜单
        return new ArrayList<>();
    }

    @Override
    @GlobalTransactional
    public void assignRoleMenus(Long id, List<Long> menuIds) throws Exception {
        // 标准实现：分配角色菜单
    }

    @Override
    public boolean checkRoleCode(String roleCode) throws Exception {
        // 标准实现：检查角色编码是否存在
        return roleMapper.checkRoleCodeExists(roleCode, null) > 0;
    }

    @Override
    public List<Long> getRolePermissions(Long id) throws Exception {
        // 获取角色权限ID列表
        return rolePermissionMapper.selectPermissionIdsByRoleId(id);
    }

    @Override
    @GlobalTransactional
    public void assignRolePermissions(Long id, List<Long> permissionIds) throws Exception {
        // 删除原有权限分配
        rolePermissionMapper.deleteByRoleId(id);
        
        // 新增权限分配
        if (permissionIds != null && !permissionIds.isEmpty()) {
            List<RolePermission> rolePermissions = permissionIds.stream()
                    .map(permissionId -> {
                        RolePermission rolePermission = new RolePermission();
                        rolePermission.setRoleId(id);
                        rolePermission.setPermissionId(permissionId);
                        rolePermission.setStatus(1);
                        return rolePermission;
                    })
                    .collect(Collectors.toList());
            
            rolePermissionMapper.batchInsert(rolePermissions);
        }
    }

    @Override
    public Long getRoleIdByCode(String roleCode) throws Exception {
        if (roleCode == null || roleCode.trim().isEmpty()) {
            return null;
        }
        
        Role role = roleMapper.selectByRoleCode(roleCode.trim());
        return role != null ? role.getId() : null;
    }
    
    /**
     * 将Role实体转换为RoleVO
     */
    private RoleVO convertToVO(Role role) {
        if (role == null) {
            return null;
        }
        
        RoleVO vo = new RoleVO();
        vo.setId(role.getId());
        vo.setRoleName(role.getRoleName());
        vo.setRoleCode(role.getRoleCode());
        vo.setDescription(role.getDescription());
        vo.setRoleType(role.getRoleType());
        vo.setDataScope(role.getDataScope());
        vo.setStatus(role.getStatus());
        vo.setSort(role.getSortOrder());
        vo.setRemark(role.getDescription()); // 使用description作为remark
        vo.setCreateTime(role.getCreateTime());
        vo.setUpdateTime(role.getUpdateTime());
        vo.setCreateBy(role.getCreateBy() != null ? role.getCreateBy().toString() : null);
        vo.setUpdateBy(role.getUpdateBy() != null ? role.getUpdateBy().toString() : null);
        vo.setIsBuiltin(role.getIsBuiltin());
        return vo;
    }
} 